﻿@page "/modulelogs"

@using Gurux.DLMS.AMI.Shared.DIs

@using Gurux.DLMS.AMI.Shared.Enums
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.Rest
@using Microsoft.AspNetCore.SignalR.Client
@using Gurux.DLMS.AMI.Shared
@using Gurux.DLMS.AMI.Client.Helpers
@using Gurux.DLMS.AMI.Module
@using System.Diagnostics

@attribute [Authorize(Roles = "Admin, ModuleLogManager")]
@inject NavigationManager NavigationManager
@inject HttpClient Http
@inject ConfirmBase Confirm
@inject IGXNotifier2 Notifier
@implements IDisposable

@if (Title)
{
    <PageTitle>@Properties.Resources.ModuleLogs</PageTitle>
}

<AuthorizeView Roles=@GXRoles.ToString(GXRoles.Admin, GXRoles.ModuleLogManager)>
    <MenuControl RightCorner="true">
        <ChildContent>
            <MenuItem Text="@Properties.Resources.Close" Icon="oi oi-pencil" OnClick="@OnClose" />
            <MenuItem Text="@Properties.Resources.Clear" Icon="oi oi-trash" OnClick="@OnClear" />
        </ChildContent>
    </MenuControl>
</AuthorizeView>


<GXTable @ref="table"
         Context="item"
         ItemsProvider="@GetItems"
         SelectionMode="SelectionMode.Multiple"
         ShowRemoved="false"
         Filter="@Filter"
         ShowAllUsers="@Header"
         Columns="@Columns"
         CanEdit="@CanEdit"
         OnSearch="@Updated">
    <FilterContent>
        <th>
            <input class="form-control" placeholder="按创建时间..."
                   type="datetime-local"
                   @onchange="@((ChangeEventArgs __e) => filter.CreationTime = @StatusTile.ToDateTime(__e.Value))" />
        </th>
        <th>
            <ModuleSelector @bind-Value="@filter.Module"></ModuleSelector>
        </th>
        <th>
            <input class="form-control" type="text" placeholder="Filter by log..."
                   @onchange="@((ChangeEventArgs __e) => filter.Message = Convert.ToString(__e.Value))" />
        </th>
        <th>
            <div>
                <TraceLevelSearch @bind-Value="@TraceLevel"></TraceLevelSearch>
            </div>
        </th>
        <th>
            <input class="form-control" placeholder="按关闭时间..."
                   type="datetime-local"
                   @onchange="@((ChangeEventArgs __e) => filter.Closed = @StatusTile.ToDateTime(__e.Value))" />
        </th>
    </FilterContent>
    <MenuContent>
        <ContextMenuItem Text="@Properties.Resources.Show" Icon="oi oi-eye" OnClick="async () => OnShow()"></ContextMenuItem>
        <ContextMenuItem Text="@Properties.Resources.Close" Icon="oi oi-pencil" OnClick="async () => OnClose()"></ContextMenuItem>
    </MenuContent>
    <HeaderContent>
        <Th Id="CreationTime" SortMode="SortMode.Descending">@Properties.Resources.CreationTime</Th>
            <th>@Properties.Resources.Module</th>
        <th>@Properties.Resources.Error</th>
        <th>@Properties.Resources.Level</th>
        <th>@Properties.Resources.CloseTime</th>
    </HeaderContent>
    <ItemContent>
        <Td Link="@("Config/ModuleLog/Edit/" + item.Id)">@item.CreationTime</Td>
            <td>@item.Module</td>
        <td>@item.Message</td>
        <td>@ClientHelpers.LevelToString(item.Level)</td>
        <td>@item.Closed</td>
    </ItemContent>
</GXTable>
<br />
<Confirm @ref="ClearConfirmation"
         ConfirmationChanged="OnClearConfirmation"
         ConfirmationTitle=@Properties.Resources.ConfirmDataClear
         AllowDelete="false"
         OkTitle="@Properties.Resources.Clear"
         ConfirmationMessage="@Properties.Resources.AreYouSureYouWantToClearLog">
</Confirm>
<Confirm @ref="CloseConfirmation"
         ConfirmationChanged="OnCloseConfirmation"
         ConfirmationTitle="Confirm close"
         AllowDelete="false"
         OkTitle="@Properties.Resources.Close"
         ConfirmationMessage="@Properties.Resources.AreYouSureYouWantToCloseSelectedItems">
</Confirm>

@code {
    /// <summary>
    /// Selected module log ID.
    /// </summary>
    [Parameter]
    public Guid? Id { get; set; }

    /// <summary>
    /// User action.
    /// </summary>
    [Parameter]
    public string? Action { get; set; }

    /// <inheritdoc />
    public string Name
    {
        get
        {
            return Gurux.DLMS.AMI.Client.Properties.Resources.ModuleLogs;
        }
    }

    private TraceLevel TraceLevel
    {
        get
        {
            return (TraceLevel)filter.Level.GetValueOrDefault();
        }
        set
        {
            if (filter != null)
            {
                if (value == TraceLevel.Off)
                {
                    //If filter is not used.
                    filter.Level = null;
                }
                else
                {
                    filter.Level = (int)value;
                }
            }
        }
    }

    /// <inheritdoc />
    public Type? ConfigurationUI
    {
        get
        {
            return null;
        }
    }

    /// <inheritdoc />
    public string? Icon
    {
        get
        {
            return "oi oi-tablet";
        }
    }

    /// <summary>
    /// Amount of the module logs shown on the view.
    /// </summary>
    [Parameter]
    public int Count { get; set; } = 0;

    /// <summary>
    /// Is filter shown.
    /// </summary>
    [Parameter]
    public bool Filter { get; set; } = true;

    /// <summary>
    /// Is header shown.
    /// </summary>
    [Parameter]
    public bool Header { get; set; } = true;

    /// <summary>
    /// Is edit allowed.
    /// </summary>
    [Parameter]
    public bool CanEdit { get; set; } = true;

    /// <summary>
    /// Available columns.
    /// </summary>
    [Parameter]
    public string[]? Columns { get; set; }

    /// <summary>
    /// Is title shown.
    /// </summary>
    [Parameter]
    public bool Title { get; set; } = true;

    /// <summary>
    /// Module log filter.
    /// </summary>
    private GXModuleLog filter = new GXModuleLog()
        {
            Level = null
        };
    /// <summary>
    /// User is verified before module logs are cleared.
    /// </summary>
    protected ConfirmBase? ClearConfirmation;

    /// <summary>
    /// User is verified before module errors are closed.
    /// </summary>
    protected ConfirmBase? CloseConfirmation;

    /// <summary>
    /// Closed errors are shown.
    /// </summary>
    public bool ShowClosedErrors { get; set; }

    /// <summary>
    /// Active item.
    /// </summary>
    public GXModuleLog? Active
    {
        get
        {
            return table?.Active;
        }
    }

    /// <summary>
    /// Table reference.
    /// </summary>
    protected GXTable<GXModuleLog>? table;

    /// <summary>
    /// Update table.
    /// </summary>
    protected async Task Updated()
    {
        try
        {
            if (table != null)
            {
                Notifier.ClearStatus();
                await table.RefreshDataAsync(true);
            }
        }
        catch (Exception ex)
        {
            Notifier.ProcessError(ex);
        }
    }

    protected override void OnInitialized()
    {
        try
        {
            if (string.Compare(Action, "Edit", true) == 0)
            {
                //If user edist the module log.
                return;
            }
            if (Notifier == null)
            {
                throw new ArgumentException(Properties.Resources.InvalidNotifier);
            }
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            Notifier.On<IEnumerable<GXModule>?>(this, nameof(IGXHubEvents.ClearModuleLogs), async (logs) =>
            {
                await Updated();
            });
            Notifier.On<IEnumerable<GXModuleLog>>(this, nameof(IGXHubEvents.AddModuleLogs), async (logs) =>
            {
                await Updated();
            });
            Notifier.On<IEnumerable<GXModuleLog>>(this, nameof(IGXHubEvents.CloseModuleLogs), async (logs) =>
            {
                await Updated();
            });
            Notifier.Clear();
            Notifier.UpdateButtons();
            if (table != null && Id != null)
            {
                //Get last selected item.
                table.Active = new GXModuleLog() { Id = Id.Value };
            }
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier.ProcessError(ex);
        }
        finally
        {
            Notifier.ProgressEnd();
        }
    }

    private async ValueTask<ItemsProviderResult<GXModuleLog>> GetItems(GXItemsProviderRequest request)
    {
        //Don't clear status or error is lost.
        Notifier.ProgressStart();
        try
        {
            if (ShowClosedErrors)
            {
                //Show closed errors.
                filter.Closed = DateTimeOffset.MaxValue;
            }
            else
            {
                //Show active errors.
                filter.Closed = null;
            }
            if (string.IsNullOrEmpty(filter.Module?.Id))
            {
                filter.Module = null;
            }
            else
            {
                //Send only ID if module filter is used.
                filter.Module = new GXModule()
                    {
                        Id = filter.Module.Id
                    };
            }
            ListModuleLogs req = new ListModuleLogs()
                {
                    Index = request.StartIndex,
                    Count = request.Count,
                    Filter = filter,
                    OrderBy = request.OrderBy,
                    Descending = request.Descending,
                    AllUsers = request.ShowAllUserData
                };
            if (Count != 0)
            {
                req.Count = Count;
            }
            var ret = await Http.PostAsJson<ListModuleLogsResponse>("api/ModuleLog/List", req, request.CancellationToken);
            if (ret.Logs != null)
            {
                //Mark module logs as seen.
                await Notifier.Mark(Http, TargetType.ModuleLog, ret.Logs.Max(s => s.CreationTime));
                return new ItemsProviderResult<GXModuleLog>(ret.Logs, ret.Count);
            }
        }
        catch (TaskCanceledException)
        {
            //Let the table component handle this.
            throw;
        }
        catch (Exception ex)
        {
            Notifier.ProcessError(ex);
        }
        finally
        {
            Notifier.ProgressEnd();
        }
        return default;
    }

    /// <summary>
    /// Show module log details.
    /// </summary>
    public void OnShow()
    {
        try
        {
            Notifier.ClearStatus();
            if (table?.Active == null)
            {
                throw new Exception(Gurux.DLMS.AMI.Client.Properties.Resources.NoItemIsSelected);
            }
            ClientHelpers.NavigateTo(NavigationManager, Notifier, "Config/ModuleLog/Edit/" + table.Active.Id);
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier.ProcessError(ex);
        }
    }

    /// <summary>
    /// Close the selected logs.
    /// </summary>
    public void OnClose()
    {
        try
        {
            if (table == null || !table.SingleOrDefault().Any())
            {
                throw new Exception(Gurux.DLMS.AMI.Client.Properties.Resources.NoItemIsSelected);
            }
            CloseConfirmation?.Show(table?.SingleOrDefault()?.Select(s => s.Message).ToArray());
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier.ProcessError(ex);
        }
    }

    /// <summary>
    /// Close the selected logs.
    /// </summary>
    public async Task OnCloseConfirmation(ConfirmArgs args)
    {
        try
        {
            if (table != null && args.Confirm)
            {
                CloseAgentLog req = new CloseAgentLog()
                    {
                        Logs = table.SingleOrDefault().Select(w => w.Id).ToArray()
                    };
                await Http.PostAsJson<CloseAgentLogResponse>("api/ModuleLog/Close", req);
            }
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier.ProcessError(ex);
        }
    }

    /// <summary>
    /// Clear the module logs.
    /// </summary>
    public void OnClear()
    {
        Notifier.ClearStatus();
        ClearConfirmation?.Show();
    }

    /// <summary>
    /// Clear the agent error list.
    /// </summary>
    public async Task OnClearConfirmation(ConfirmArgs args)
    {
        try
        {
            if (args.Confirm)
            {
                await Http.PostAsJson<ClearModuleLogsResponse>("api/ModuleLog/Clear", new ClearModuleLogs());
            }
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier.ProcessError(ex);
        }
    }

    public void Dispose()
    {
        Notifier.RemoveListener(this);
    }
}
